package com.shujia.mllib
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.classification.{NaiveBayes, NaiveBayesModel}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import scala.util.Try


object Test2 {
  def main(args: Array[String]): Unit = {
    // 1. 初始化 Spark
    val conf = new SparkConf()
      .setAppName("Test2")
      .setMaster("local[*]")
    val sc = new SparkContext(conf)
    // 2. 加载并预处理数据
    val rawData = sc.textFile("spark/data/football_matches.csv")
      .filter(!_.startsWith("result")) // 过滤标题行
    val parsedData = rawData.map { line =>
      val cols = line.split(",")
      val label = cols(6) match {
        case "胜" => 0.0
        case "平" => 1.0
        case "负" => 2.0
      }
      val features = Vectors.dense(
        cols(0).toDouble, // attack_goals
        cols(1).toDouble, // defense_conceded
        cols(2).toDouble, // possession
        cols(3).toDouble, // shots_on_target
        cols(4).toDouble, // fouls
        cols(5).toDouble // home_advantage
      )
      LabeledPoint(label, features)
    }
    // 3. 划分数据集
    val Array(trainData, testData) = parsedData.randomSplit(Array(0.8, 0.2))
    // 4. 训练模型
    val model = NaiveBayes.train(input = trainData, lambda = 1.0, modelType = "multinomial")
    // 5. 评估模型
    val testPredictions = testData.map { point =>
      // 对每个测试样本进行预测，生成(预测值, 真实值)的二元组
      // 将测试集数据转化为(预测结果, 真实标签)的元组集合
      (model.predict(point.features), point.label)
    }
    //预测正确的样本数/总样本数
    val accuracy = testPredictions.filter(x => x._1 == x._2).count().toDouble / testData.count()
    println(f"[模型评估] 测试集准确率: ${accuracy * 100}%.2f%%")




    // 6. 用户交互预测
    val labelMap = Map(0.0 -> "胜", 1.0 -> "平", 2.0 -> "负")
    var userInput = ""
    while ({
      println("\n=== 输入新比赛数据 ===")
      print("格式: 进攻进球,防守失球,控球率%,射正次数,犯规次数,主场(1/0)\n> ")
      userInput = scala.io.StdIn.readLine().trim
      userInput.nonEmpty && !userInput.equalsIgnoreCase("exit")
    }) {
      Try {
        val features = userInput.split(",").map(_.toDouble)
        require(features.length == 6, "必须输入6个数值特征")
        Vectors.dense(features)
      } match {
        case scala.util.Success(vector) =>
          val prediction = model.predict(vector)
          println(s"预测结果: ${labelMap(prediction)}")
          // 显示详细概率
          val probabilities = model.predictProbabilities(vector)
          println("概率分布:")
          labelMap.foreach { case (k, v) =>
            println(f" $v: ${probabilities(k.toInt) * 100}%.1f%%")
          }
        case scala.util.Failure(ex) =>
          println(s"输入错误: ${ex.getMessage}")
      }
    }
    sc.stop()
  }
}